// app.js
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log('登录成功', res.code)
      }
    })

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })

    // 初始化默认数据
    this.initDefaultData()
  },

  globalData: {
    userInfo: null,
    systemInfo: null
  },

  // 初始化默认数据
  initDefaultData() {
    // 初始化用户信息
    if (!wx.getStorageSync('userInfo')) {
      const defaultUserInfo = {
        name: '张三',
        id: '2024001',
        level: '黄金志愿者',
        avatar: '/images/avatar-default.png',
        points: 1280,
        serviceCount: 15,
        serviceDays: 365
      }
      wx.setStorageSync('userInfo', defaultUserInfo)
    }

    // 初始化积分数据
    if (!wx.getStorageSync('pointsData')) {
      const defaultPointsData = {
        totalPoints: 1280,
        stats: {
          earned: 1500,
          used: 220,
          available: 1280
        },
        records: [
          {
            id: '1',
            title: '参与遗体捐献宣传进社区',
            time: '2024-01-15 09:00',
            points: 50,
            type: 'earned'
          },
          {
            id: '2',
            title: '每日签到',
            time: '2024-01-15 08:00',
            points: 10,
            type: 'earned'
          },
          {
            id: '3',
            title: '兑换纪念品',
            time: '2024-01-14 15:30',
            points: 100,
            type: 'used'
          }
        ]
      }
      wx.setStorageSync('pointsData', defaultPointsData)
    }

    // 初始化用户活动数据
    if (!wx.getStorageSync('userActivities')) {
      const defaultActivities = [
        {
          activityId: '1',
          activityTitle: '遗体捐献宣传进社区',
          joinTime: '2024-01-15T09:00:00.000Z',
          status: 'registered',
          points: 50
        }
      ]
      wx.setStorageSync('userActivities', defaultActivities)
    }

    // 初始化志愿者注册数据
    if (!wx.getStorageSync('volunteerRegistrations')) {
      wx.setStorageSync('volunteerRegistrations', [])
    }

    // 获取系统信息
    wx.getSystemInfo({
      success: res => {
        this.globalData.systemInfo = res
      }
    })
  },

  // 检查登录状态
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo')
    return !!userInfo
  },

  // 获取用户信息
  getUserInfo() {
    return wx.getStorageSync('userInfo') || null
  },

  // 更新用户信息
  updateUserInfo(userInfo) {
    wx.setStorageSync('userInfo', userInfo)
    this.globalData.userInfo = userInfo
  },

  // 获取积分数据
  getPointsData() {
    return wx.getStorageSync('pointsData') || null
  },

  // 更新积分数据
  updatePointsData(pointsData) {
    wx.setStorageSync('pointsData', pointsData)
  },

  // 添加积分记录
  addPointsRecord(record) {
    const pointsData = this.getPointsData()
    if (pointsData) {
      pointsData.records.unshift(record)
      if (record.type === 'earned') {
        pointsData.totalPoints += record.points
        pointsData.stats.earned += record.points
        pointsData.stats.available += record.points
      } else if (record.type === 'used') {
        pointsData.totalPoints -= record.points
        pointsData.stats.used += record.points
        pointsData.stats.available -= record.points
      }
      this.updatePointsData(pointsData)
    }
  },

  // 显示成功提示
  showSuccess(message, duration = 2000) {
    wx.showToast({
      title: message,
      icon: 'success',
      duration: duration
    })
  },

  // 显示错误提示
  showError(message, duration = 2000) {
    wx.showToast({
      title: message,
      icon: 'none',
      duration: duration
    })
  },

  // 显示加载提示
  showLoading(message = '加载中...') {
    wx.showLoading({
      title: message,
      mask: true
    })
  },

  // 隐藏加载提示
  hideLoading() {
    wx.hideLoading()
  },

  // 确认对话框
  showConfirm(title, content, callback) {
    wx.showModal({
      title: title,
      content: content,
      success: res => {
        if (res.confirm && callback) {
          callback(true)
        } else if (res.cancel && callback) {
          callback(false)
        }
      }
    })
  }
})
